from fastapi import FastAPI
from enum import Enum

app = FastAPI()


class ModelName(str, Enum):  # 继承str，这样api文档就能把值等已成字符串并成功渲染
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/items/{item_id}")  # 传参
async def read_item(item_id: int):  # 可以通过类型声明自动解析
    return {"item_id": item_id}


@app.get("/models/{model_name}")  # 使用枚举类型
async def get_model(model_name: ModelName):
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}
    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}
    return {"model_name": model_name, "message": "Have some residuals"}


@app.get(
    "/files/{file_path:path}")  # 包含路径的路径参数，注意，包含 /home/johndoe/myfile.txt 的路径参数要以斜杠（/）开头。本例中的 URL 是 /files//home/johndoe/myfile.txt。注意，files 和 home 之间要使用双斜杠（//）。
async def read_file(file_path: str):
    return {"file_path": file_path}


fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int | None = None, limit: int = 10):  # 进行格式转换，并设默认值，在网页中为http://127.0.0.1:8000/items/?skip=0&limit=10
    return skip,limit

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None): #q为可选参数，注意，FastAPI 可以识别出 item_id 是路径参数，q 不是路径参数，而是查询参数。
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None, short: bool = False): #定义成bool类型并转换，不管是什么字符，都是true
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

@app.get("/users/{user_id}/items/{item_id}")#多个参数
async def read_user_item(
    user_id: int, item_id: str, q: str | None = None, short: bool = False
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

@app.get("/items/{item_id}")
async def read_user_item(
    item_id: str, needy: str, skip: int = 0, limit: int | None = None
): #可以同时设置不同的变量，有默认值的，可选的，没有默认值的，必填
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return

